package com.example.aicode.chat.tools;

import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class CodeQuestionTool {

    @Tool(name = "searchCodeQuestion" ,value = """
            url :www.mianshiya.com
            This tool is designed to help you efficiently search for problem lists on LeetCode using specific keywords.
            To use it, simply input the keyword related to the problems you are looking for.
             The tool will then query LeetCode's database and retrieve a list of problems that match the given keywords.
         """)
    public String searchCodeQuestion(@P("the keyword to search") String keyword) {
        List<String> questions = new ArrayList<>();
        String encodeKeyword= URLEncoder.encode(keyword, StandardCharsets.UTF_8);
        String url="https://www.mianshiya.com/search/all?searchText="+encodeKeyword;
        //发送请求并解析页面
        Document doc;
        try {
            doc= Jsoup.connect(url).userAgent("Mozilla/5.8").timeout(5000).get();
        }catch (Exception e){
            log.error(e.getMessage());
            return e.getMessage();
        }
        Elements questionsElements = doc.select(".ant-table-cell > a");
        questionsElements.forEach(question -> questions.add(question.text().trim()));
        return String.join("\n", questions);
    }
}
